package com.qdhh.enrollment.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qdhh.enrollment.common.Result;
import com.qdhh.enrollment.dto.QuizSubmissionQueryDTO;
import com.qdhh.enrollment.dto.QuestionImportDTO;
import com.qdhh.enrollment.service.QuizService;
import com.qdhh.enrollment.service.QuizSubmissionService;
import com.qdhh.enrollment.vo.QuizSubmissionVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Tag(name = "管理员-考试管理", description = "管理员考试管理接口，包括题目导入、考试记录查询等")
@RestController
@RequestMapping("/api/admin/quiz")
public class AdminQuizController {

    private final QuizService quizService;
    private final QuizSubmissionService submissionService;

    public AdminQuizController(QuizService quizService,
                               QuizSubmissionService submissionService) {
        this.quizService = quizService;
        this.submissionService = submissionService;
    }

    @Operation(summary = "导入题目", description = "管理员接口：通过CSV或Excel文件导入题目")
    @PostMapping("/import")
    public Result<QuestionImportDTO> importQuestions(
            @Parameter(description = "题目文件（CSV或Excel格式）") @RequestParam("file") MultipartFile file) {
        try {
            // 验证文件
            if (file.isEmpty()) {
                return Result.failure(400, "文件不能为空");
            }
            
            String filename = file.getOriginalFilename();
            if (filename == null || (!filename.endsWith(".csv") && !filename.endsWith(".xlsx"))) {
                return Result.failure(400, "只支持 CSV 或 Excel 文件");
            }
            
            // 导入题目
            QuestionImportDTO result = quizService.importQuestionsFromCSV(file.getInputStream());
            
            if (result.getSuccessCount() > 0) {
                return Result.success("导入成功", result);
            } else {
                return Result.failure(400, "未导入任何题目", result);
            }
        } catch (IOException e) {
            return Result.failure(500, "文件读取失败: " + e.getMessage());
        } catch (Exception e) {
            return Result.failure(500, "导入失败: " + e.getMessage());
        }
    }

    @Operation(summary = "下载导入模板", description = "管理员接口：获取题目导入模板内容")
    @GetMapping("/template")
    public Result<String> downloadTemplate() {
        StringBuilder csv = new StringBuilder();
        csv.append("分类,题目类型,题目内容,选项A,选项B,选项C,选项D,正确答案\n");
        csv.append("\"安全教育\",single,\"学校图书馆开放时间是？\",\"8:00-18:00\",\"8:00-20:00\",\"9:00-21:00\",\"10:00-22:00\",B\n");
        csv.append("\"安全教育\",multiple,\"以下哪些是学校的主要建筑？\",\"教学楼\",\"图书馆\",\"运动场\",\"食堂\",\"A,B,C\"\n");
        csv.append("\"校园常识\",truefalse,\"遇到火灾时，应该乘坐电梯逃生。\",,,,\"错误\",错误\n");
        
        return Result.success("模板内容", csv.toString());
    }
    
    @Operation(summary = "查询考试记录", description = "管理员接口：分页查询所有学生的考试记录，支持多条件筛选")
    @GetMapping("/submissions")
    public Result<Map<String, Object>> querySubmissions(
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "minScore", required = false) Integer minScore,
            @RequestParam(value = "maxScore", required = false) Integer maxScore,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        
        // 构建查询DTO
        QuizSubmissionQueryDTO queryDTO = new QuizSubmissionQueryDTO();
        queryDTO.setName(name);
        queryDTO.setMinScore(minScore);
        queryDTO.setMaxScore(maxScore);
        queryDTO.setStartTime(startTime);
        queryDTO.setEndTime(endTime);
        queryDTO.setPage(page);
        queryDTO.setSize(pageSize);
        
        // 查询数据
        IPage<QuizSubmissionVO> pageResult = submissionService.querySubmissions(queryDTO);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("records", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("page", pageResult.getCurrent());
        result.put("pageSize", pageResult.getSize());
        
        return Result.success("查询成功", result);
    }
}

